using System.Net.Http;

namespace SmartMedical.WinUI
{
    /// <summary>
    /// 医疗卡办理窗体
    /// 提供患者医疗卡申请和办理功能
    /// </summary>
    public partial class MedicalCardForm : Form
    {
        #region 私有字段
        /// <summary>
        /// HTTP客户端，用于API调用
        /// </summary>
        private readonly HttpClient _httpClient;

        /// <summary>
        /// API基础URL
        /// </summary>
        private const string API_BASE_URL = "http://localhost:5165";
        #endregion

        #region 构造函数
        /// <summary>
        /// 初始化医疗卡办理窗体
        /// </summary>
        public MedicalCardForm()
        {
            InitializeComponent();
            _httpClient = new HttpClient();
            InitializeForm();
        }
        #endregion

        #region 初始化方法
        /// <summary>
        /// 初始化窗体设置
        /// </summary>
        private void InitializeForm()
        {
            this.Text = "医疗卡办理";
            this.Size = new Size(1414, 847);
            this.StartPosition = FormStartPosition.CenterParent;
            this.MaximizeBox = true;
            this.MinimizeBox = true;
            this.FormBorderStyle = FormBorderStyle.Sizable;

            // 初始化下拉框数据
            InitializeComboBoxes();

            // 设置默认值
            SetDefaultValues();
        }

        /// <summary>
        /// 初始化下拉框数据和单选按钮
        /// </summary>
        private void InitializeComboBoxes()
        {
            // 性别单选按钮默认选择
            rbMale.Checked = true;

            // 婚姻状况单选按钮默认选择
            rbSingle.Checked = true;

            // 民族下拉框
            cmbEthnicity.Items.Clear();
            cmbEthnicity.Items.AddRange(new string[] { "汉族", "蒙古族", "回族", "藏族", "维吾尔族", "苗族", "彝族", "壮族", "布依族", "朝鲜族", "满族", "侗族", "瑶族", "白族", "土家族", "哈尼族", "哈萨克族", "傣族", "黎族", "傈僳族", "佤族", "畲族", "高山族", "拉祜族", "水族", "东乡族", "纳西族", "景颇族", "柯尔克孜族", "土族", "达斡尔族", "仫佬族", "羌族", "布朗族", "撒拉族", "毛南族", "仡佬族", "锡伯族", "阿昌族", "普米族", "塔吉克族", "怒族", "乌孜别克族", "俄罗斯族", "鄂温克族", "德昂族", "保安族", "裕固族", "京族", "塔塔尔族", "独龙族", "鄂伦春族", "赫哲族", "门巴族", "珞巴族", "基诺族" });
            cmbEthnicity.SelectedIndex = 0;

            // 文化程度下拉框
            cmbEducation.Items.Clear();
            cmbEducation.Items.AddRange(new string[] { "小学", "初中", "高中", "中专", "大专", "本科", "硕士", "博士" });
            cmbEducation.SelectedIndex = 3;
        }

        /// <summary>
        /// 设置默认值
        /// </summary>
        private void SetDefaultValues()
        {
            // 设置默认出生日期
            dtpBirthDate.Value = DateTime.Now.AddYears(-30);

            // 自动计算年龄
            CalculateAge();
        }
        #endregion

        #region 事件处理方法
        /// <summary>
        /// 确定按钮点击事件
        /// </summary>
        private async void BtnConfirm_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证输入
                if (!ValidateInput())
                {
                    return;
                }

                // 禁用按钮防止重复提交
                btnConfirm.Enabled = false;
                btnConfirm.Text = "办理中...";

                // 构建医疗卡数据
                var medicalCardData = new MedicalCardData
                {
                    PatientId = GeneratePatientId(), // 生成临时患者ID
                    PatientName = txtName.Text.Trim(),
                    Gender = rbMale.Checked ? 1 : 0, // 1-男, 0-女
                    Age = int.Parse(txtAge.Text),
                    BirthDate = dtpBirthDate.Value,
                    Phone = txtPhone.Text.Trim(),
                    Address = txtAddress.Text.Trim(),
                    IdCard = txtIdCard.Text.Trim(),
                    Ethnicity = cmbEthnicity.SelectedItem?.ToString() ?? "",
                    Education = cmbEducation.SelectedItem?.ToString() ?? "",
                    Occupation = txtPosition.Text.Trim(),
                    PostalCode = txtPostalCode.Text.Trim(),
                    MaritalStatus = rbMarried.Checked ? "已婚" : "未婚"
                };

                // 调用API办理医疗卡
                var result = await CreateMedicalCardAsync(medicalCardData);

                if (result.Success)
                {
                    MessageBox.Show($"医疗卡办理成功！\n医疗卡号：{result.CardNo}\n办卡类型：{medicalCardData.CardType}\n办卡费用：{medicalCardData.CardFee:C}", 
                        "办理成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    MessageBox.Show($"办理失败：{result.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"办理失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复按钮状态
                btnConfirm.Enabled = true;
                btnConfirm.Text = "注册";
            }
        }

        /// <summary>
        /// 初始化按钮点击事件
        /// </summary>
        private void BtnCancel_Click(object sender, EventArgs e)
        {
            // 清空所有输入框
            txtName.Text = string.Empty;
            txtAddress.Text = string.Empty;
            txtPhone.Text = string.Empty;
            txtPosition.Text = string.Empty;
            txtPostalCode.Text = string.Empty;
            txtIdCard.Text = string.Empty;

            // 重置单选按钮
            rbMale.Checked = true;
            rbSingle.Checked = true;

            // 重置下拉框
            cmbEthnicity.SelectedIndex = 0;
            cmbEducation.SelectedIndex = 3;

            // 重置日期
            dtpBirthDate.Value = DateTime.Now.AddYears(-30);

            // 重新计算年龄
            CalculateAge();

            MessageBox.Show("表单已初始化！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 出生日期变化事件
        /// </summary>
        private void DtpBirthDate_ValueChanged(object sender, EventArgs e)
        {
            // 自动计算年龄
            CalculateAge();
        }
        #endregion

        #region 辅助方法
        /// <summary>
        /// 验证输入数据
        /// </summary>
        /// <returns>验证是否通过</returns>
        private bool ValidateInput()
        {
            // 验证姓名
            if (string.IsNullOrWhiteSpace(txtName.Text))
            {
                MessageBox.Show("请输入姓名！", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtName.Focus();
                return false;
            }

            // 验证身份证号
            if (string.IsNullOrWhiteSpace(txtIdCard.Text))
            {
                MessageBox.Show("请输入身份证号！", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtIdCard.Focus();
                return false;
            }

            // 验证电话
            if (string.IsNullOrWhiteSpace(txtPhone.Text))
            {
                MessageBox.Show("请输入联系电话！", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtPhone.Focus();
                return false;
            }

            return true;
        }

        /// <summary>
        /// 计算年龄
        /// </summary>
        private void CalculateAge()
        {
            var today = DateTime.Today;
            var age = today.Year - dtpBirthDate.Value.Year;
            if (dtpBirthDate.Value.Date > today.AddYears(-age))
                age--;

            txtAge.Text = age.ToString();
        }

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            // 释放HTTP客户端资源
            _httpClient?.Dispose();
            base.OnFormClosed(e);
        }
        #endregion

        private void groupBoxPersonalInfo_Enter(object sender, EventArgs e)
        {

        }

        #region API调用方法
        /// <summary>
        /// 调用后端API办理医疗卡
        /// </summary>
        /// <param name="data">医疗卡数据</param>
        /// <returns>办理结果</returns>
        private async Task<CreatePatientResult> CreateMedicalCardAsync(MedicalCardData data)
        {
            try
            {
                var json = System.Text.Json.JsonSerializer.Serialize(data);
                var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
                
                var response = await _httpClient.PostAsync($"{API_BASE_URL}/api/Medical/CreateMedicalCard", content);
                var responseContent = await response.Content.ReadAsStringAsync();
                
                if (response.IsSuccessStatusCode)
                {
                    var apiResult = System.Text.Json.JsonSerializer.Deserialize<ApiResponse<string>>(responseContent, new System.Text.Json.JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    });
                    
                    if (apiResult?.Code == 200)
                    {
                        return new CreatePatientResult
                        {
                            Success = true,
                            PatientId = 0, // 医疗卡办理API不返回患者ID
                            CardNo = apiResult.Data ?? GenerateCardNo(),
                            Message = apiResult.Msg ?? "医疗卡办理成功"
                        };
                    }
                    else
                    {
                        return new CreatePatientResult
                        {
                            Success = false,
                            Message = apiResult?.Msg ?? "医疗卡办理失败"
                        };
                    }
                }
                else
                {
                    return new CreatePatientResult
                    {
                        Success = false,
                        Message = $"服务器错误：{response.StatusCode}"
                    };
                }
            }
            catch (Exception ex)
            {
                return new CreatePatientResult
                {
                    Success = false,
                    Message = $"网络错误：{ex.Message}"
                };
            }
        }
        
        /// <summary>
        /// 生成医疗卡号
        /// </summary>
        /// <returns>医疗卡号</returns>
        private string GenerateCardNo()
        {
            var dateStr = DateTime.Now.ToString("yyyyMMdd");
            var random = new Random().Next(1000, 9999);
            return $"{dateStr}{random}";
        }
        
        /// <summary>
        /// 生成患者ID
        /// </summary>
        /// <returns>患者ID</returns>
        private long GeneratePatientId()
        {
            // 使用时间戳和随机数生成唯一的患者ID
            var timestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
            var random = new Random().Next(100, 999);
            return timestamp * 1000 + random;
        }
        #endregion
    }

    #region 数据模型类
    /// <summary>
    /// 医疗卡申请数据模型
    /// </summary>
    public class MedicalCardData
    {
        /// <summary>
        /// 患者ID（必填）
        /// </summary>
        public long PatientId { get; set; }
        
        /// <summary>
        /// 患者姓名
        /// </summary>
        public string PatientName { get; set; } = string.Empty;

        /// <summary>
        /// 医疗卡号
        /// </summary>
        public string? CardNo { get; set; }

        /// <summary>
        /// 身份证号
        /// </summary>
        public string IdCard { get; set; } = string.Empty;

        /// <summary>
        /// 性别 (0-女, 1-男)
        /// </summary>
        public int Gender { get; set; }

        /// <summary>
        /// 年龄
        /// </summary>
        public int Age { get; set; }

        /// <summary>
        /// 出生日期
        /// </summary>
        public DateTime BirthDate { get; set; }

        /// <summary>
        /// 联系电话
        /// </summary>
        public string Phone { get; set; } = string.Empty;

        /// <summary>
        /// 地址
        /// </summary>
        public string Address { get; set; } = string.Empty;

        /// <summary>
        /// 民族
        /// </summary>
        public string Ethnicity { get; set; } = string.Empty;

        /// <summary>
        /// 文化程度
        /// </summary>
        public string Education { get; set; } = string.Empty;

        /// <summary>
        /// 职业
        /// </summary>
        public string Occupation { get; set; } = string.Empty;

        /// <summary>
        /// 邮政编码
        /// </summary>
        public string PostalCode { get; set; } = string.Empty;

        /// <summary>
        /// 婚姻状况
        /// </summary>
        public string MaritalStatus { get; set; } = string.Empty;
        
        /// <summary>
        /// 办卡类型（新办、补办、换卡等）
        /// </summary>
        public string CardType { get; set; } = "新办";
        
        /// <summary>
        /// 办卡费用
        /// </summary>
        public decimal CardFee { get; set; } = 10.00m;
        
        /// <summary>
        /// 操作员
        /// </summary>
        public string Operator { get; set; } = "系统";
        
        /// <summary>
        /// 办理地点
        /// </summary>
        public string IssueLocation { get; set; } = "挂号窗口";
        
        /// <summary>
        /// 备注信息
        /// </summary>
        public string? Remarks { get; set; }
        
        /// <summary>
        /// 是否首次办卡
        /// </summary>
        public bool IsFirstTime { get; set; } = true;
        
        /// <summary>
        /// 原卡号（补办或换卡时使用）
        /// </summary>
        public string? OriginalCardNo { get; set; }
    }

    /// <summary>
    /// 创建患者结果
    /// </summary>
    public class CreatePatientResult
    {
        /// <summary>
        /// 是否成功
        /// </summary>
        public bool Success { get; set; }

        /// <summary>
        /// 患者ID
        /// </summary>
        public long PatientId { get; set; }

        /// <summary>
        /// 医疗卡号
        /// </summary>
        public string CardNo { get; set; } = string.Empty;

        /// <summary>
        /// 消息
        /// </summary>
        public string Message { get; set; } = string.Empty;
    }

    /// <summary>
    /// API响应模型
    /// </summary>
    /// <typeparam name="T">数据类型</typeparam>
    public class ApiResponse<T>
    {
        /// <summary>
        /// 状态码
        /// </summary>
        public int Code { get; set; }

        /// <summary>
        /// 数据
        /// </summary>
        public T Data { get; set; } = default(T)!;

        /// <summary>
        /// 消息
        /// </summary>
        public string? Msg { get; set; }
    }
    #endregion
}